//
//  ECRegisteredViewController.m
//  Edu_iOS
//
//  Created by apple on 2017/9/9.
//  Copyright © 2017年 yanyan. All rights reserved.
//

#import "ECRegisteredViewController.h"
#import "ECServiceViewController.h"
#import "ECForgetPasswordViewController.h"

#import "ECUITextField_Account.h"
#import "CYDataHelper.h"
#import "ECRegularExpression.h"
#import "UINavigationBar+Awesome.h"
#import "ECUIVC_Mine.h"
#import "ECPrivacyAgreementVc.h"



@interface ECRegisteredViewController ()<UINavigationControllerDelegate>{
//    ECUITextField_Account *phoneArea;
    ECUITextField_Account *nameArea;
    ECUITextField_Account *passwordArea;
    ///logo背景图
    UIImageView *logoBGImageView;
    ///发送验证码之后返回的token,用于登录/注册
    NSString *tokenOfCode;
    ///服务协议勾选按钮
    ECUButton *selectBtn;
}
@property (nonatomic, strong) ECUITextField_Account *codeArea;
@property (nonatomic, strong) ECUITextField_Account *phoneArea;
@property (weak, nonatomic) IBOutlet ECUButton *returnBtn;//返回按钮

@end

@implementation ECRegisteredViewController


- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleDefault];
    [self.navigationController.navigationBar lt_reset];
    
    tokenOfCode = [[NSString alloc]init];
    
}

-(void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
    [[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleLightContent];

}


- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self.navigationController.navigationBar lt_setBackgroundColor:[[UIColor whiteColor] colorWithAlphaComponent:0]];
    
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc]initWithImage:[UIImage imageNamed:@"registered_return"] style:UIBarButtonItemStylePlain target:self action:@selector(action_dismiss)];
    
    logoBGImageView = [[UIImageView alloc]init];
    [self.view addSubview:logoBGImageView];
    logoBGImageView.image = [UIImage imageNamed:@"LoginIcon"];
    
    [logoBGImageView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_offset(0);
        make.centerX.mas_equalTo(self.view);
        make.width.mas_equalTo(@(kProportion_Width(420)));
        make.height.mas_equalTo(@(kProportion_Width(420) * 0.3514));
    }];
    [self.view layoutIfNeeded];
    self.phoneArea = [[ECUITextField_Account alloc]initWithFrame:CGRectMake(kProportion_Width(60), CGRectGetMaxY(logoBGImageView.frame) + kProportion_Width(60), kScreenWidth - kProportion_Width(60*2), kProportion_Height(Height_textfield)) placeholder:@"手机号" leftImage:[UIImage imageNamed:@"tel_user"]];
    [self.view addSubview:self.phoneArea];
    self.phoneArea.textField.keyboardType = UIKeyboardTypePhonePad;
    
    nameArea = [[ECUITextField_Account alloc]initWithFrame:CGRectMake(kProportion_Width(MarginLeft_Textfield), CGRectGetMaxY(self.phoneArea.frame) + kProportion_Width(MarginHeight_textfield), kScreenWidth - kProportion_Width(60*2), kProportion_Height(Height_textfield)) placeholder:@"用户名" leftImage:[UIImage imageNamed:@"registered_userName"]];
    [self.view addSubview:nameArea];
    
    passwordArea = [[ECUITextField_Account alloc]initWithFrame:CGRectMake(kProportion_Width(MarginLeft_Textfield), CGRectGetMaxY(nameArea.frame) + kProportion_Width(MarginHeight_textfield), kScreenWidth - kProportion_Width(MarginLeft_Textfield *2), kProportion_Height(Height_textfield)) placeholder:@"登录密码(至少6个字符)" leftImage:[UIImage imageNamed:@"pwd_user"]];
    passwordArea.isSecureTextEntry = YES;
    [self.view addSubview:passwordArea];
    
    self.codeArea = [[ECUITextField_Account alloc]initWithFrame:CGRectMake(kProportion_Width(MarginLeft_Textfield), CGRectGetMaxY(passwordArea.frame) + kProportion_Width(MarginHeight_textfield), kScreenWidth - kProportion_Width(MarginLeft_Textfield *2), kProportion_Height(Height_textfield)) placeholder:@"验证码" leftImage:[UIImage imageNamed:@"registered_code"]];
    self.codeArea.textField.frame = CGRectMake(self.codeArea.textField.mj_x, self.codeArea.textField.mj_y, kScreenWidth - kProportion_Width(MarginLeft_Textfield*2) - kProportion_Width(268) - 5, self.codeArea.textField.mj_h);
    [self.codeArea.rightButton setTitle:@"获取验证码" forState:0];
    self.codeArea.rightButton.titleLabel.font = [UIFont systemFontOfSize:14*kPercentage];
    [self.codeArea.rightButton setTitleColor: [UIColor colorWithHexString:@"#313131"] forState:0];
    self.codeArea.rightButton.frame = CGRectMake(CGRectGetMaxX(self.codeArea.textField.frame), 0, kProportion_Width(268), kProportion_Height(Height_textfield));
    [self.view addSubview:self.codeArea];
    __weak typeof(self) weakSelf = self;
    self.codeArea.block_rightButton = ^(id obj) {
        //获取验证码处理
        if ([ECRegularExpression isPhoneNumber:self.phoneArea.textField.text] == YES){
            [HWHttpTool post:URL_POST_SmsCodes
                      params:@{@"type":@"sms_register",
                               @"mobile": weakSelf.phoneArea.textField.text}
                     success:^(id json) {
                         if ([json[@"code"] integerValue] == 200) {
                             tokenOfCode = json[@"data"][@"token"];
                             [MBProgressHUD showTipMessageInWindow:@"获取验证码成功"];
                             [weakSelf.codeArea.rightButton openCountdown];//判断成功之后进行倒计时
                         }else{
                             [MBProgressHUD showTipMessageInWindow:json[@"message"]];//返回错误提示
                         }
            } failure:^(NSError *error) {
                NSString *str = [ECData_Json requestErrorTipWith:error];
                [MBProgressHUD showTipMessageInWindow:@"获取验证码失败"];
            }];
        }else{
            [MBProgressHUD showTipMessageInWindow:@"请输入合法的手机号"];
        }
    };
    
    UIView *lineView = [[UIView alloc]init];
    [self.codeArea addSubview:lineView];
    lineView.backgroundColor = [UIColor colorWithHexString:@"#B3B3B3"];
    [lineView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.mas_equalTo(self.codeArea.mas_centerY);
        make.right.mas_equalTo(self.codeArea.rightButton.mas_left).mas_offset(-3);
        make.height.offset(kProportion_Width(45));
        make.width.offset(1);
    }];
    
    
    //底部居中view
    UIView *bottomView = [[UIView alloc]init];
    [self.view addSubview:bottomView];
    
    selectBtn = [ECUButton buttonWithType:UIButtonTypeCustom];
    [selectBtn setBackgroundImage:[UIImage imageNamed:@"selectBtn_select"] forState:0];
    [self.view addSubview:selectBtn];
    [selectBtn addTarget:self action:@selector(selectBtn_click:) forControlEvents:UIControlEventTouchUpInside];
    selectBtn.selected = YES;
    [selectBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(self.codeArea.mas_bottom).mas_offset(kProportion_Width(60));
        make.left.mas_equalTo(self.codeArea.mas_left);
        make.width.height.mas_equalTo(@(kProportion_Width(50)));
    }];
    
    UILabel *agreeLab = [[UILabel alloc]init];
    agreeLab.text = @"我已阅读并同意";
    agreeLab.textColor = [UIColor colorWithHexString:@"#333333"];
    agreeLab.font = [UIFont systemFontOfSize:14*kPercentage];
    [self.view addSubview:agreeLab];
    [agreeLab mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.mas_equalTo(selectBtn.mas_centerY);
        make.left.mas_equalTo(selectBtn.mas_right).offset(kProportion_Width(20));
        make.height.equalTo(selectBtn.mas_height);
        make.width.equalTo(@(kProportion_Width(345)));
    }];
    
    ECUButton *serverBtn = [ECUButton buttonWithType:UIButtonTypeCustom];
    [serverBtn setTitle:@"《服务协议》" forState:0];
    serverBtn.titleLabel.font = [UIFont systemFontOfSize:14*kPercentage];
    [serverBtn setTitleColor:[UIColor colorWithHexString:@"#ff6600"] forState:0];
    [serverBtn addTarget:self action:@selector(agreeBtnClick) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:serverBtn];
    [serverBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.mas_equalTo(agreeLab.mas_centerY);
        make.left.mas_equalTo((agreeLab.mas_right)).mas_offset(-10);
        make.height.mas_equalTo(agreeLab.mas_height);
        make.width.mas_equalTo(@(kProportion_Width(300)));
    }];
    
    WeakSelf(ws);
    ECUButton *registeredBtn = [[ECUButton alloc]init];
    [self.view addSubview:registeredBtn];
    registeredBtn.layer.masksToBounds = YES;
    registeredBtn.layer.cornerRadius = 3;
    [registeredBtn setTitle:@"注册" forState:0];
    registeredBtn.titleLabel.font = [UIFont systemFontOfSize:16*kPercentage];
    [registeredBtn setAdjustsImageWhenHighlighted:NO];
    [registeredBtn addTarget:self action:@selector(registeredBtnClick) forControlEvents:UIControlEventTouchUpInside];
    [registeredBtn setBackgroundImage:[UIImage imageNamed:@"registered_btn_bg"] forState:0];
    [registeredBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(agreeLab.mas_bottom).mas_offset(kProportion_Width(60));
        make.centerX.mas_equalTo(ws.view.mas_centerX);
        make.width.mas_offset(kScreenWidth - kProportion_Width(60 * 2));
        make.height.mas_equalTo(registeredBtn.mas_width).multipliedBy(0.1406);
    }];
}

#pragma make ------btnclick
-(void)registeredBtnClick{
    DLog(@"提交按钮");
    if (selectBtn.selected == NO) {
        [MBProgressHUD showTipMessageInWindow:@"请先同意服务协议"];
        return;
    }

    
    if ([CYDataHelper isNull:self.phoneArea.textField.text] == NO) {//判断手机号是否为空
        if ([ECRegularExpression isPhoneNumber:self.phoneArea.textField.text] == YES) {//手机号是否合法
            if ([CYDataHelper isNull:nameArea.textField.text] == NO) {//判断用户名是否为空
                if ([ECRegularExpression detectionIsPasswordQualified:passwordArea.textField.text] == YES) {//判断密码是否合法
                    if ([CYDataHelper isNull:self.codeArea.textField.text] == NO) {//验证码是否为空
                        //发送请求
                        NSDictionary *dict = @{
                                               @"verifiedMobile":self.phoneArea.textField.text,
                                               @"nickname":nameArea.textField.text,
                                               @"password":passwordArea.textField.text,
                                               @"smsCode":self.codeArea.textField.text,
                                               @"type":@"sms_register",
                                               @"token":tokenOfCode
                                               };
                        [HWHttpTool postWithHUD:self.view WithUrl:URL_POST_Users params:dict success:^(id json) {
                            if ([json[@"code"] integerValue] == 200) {//返回成功
                                // 保存token
                                [UserInfoManager configInfo:@{@"token":json[@"data"][@"token"]}];//暂时只保存token
                                [UserInfoManager configInfo:@{@"nickName":json[@"data"][@"nickname"]}];//姓名
                                
                                NSString *imageUrl = json[@"data"][@"smallAvatar"];
                                [UserInfoManager configInfo:@{@"smallAvatar":imageUrl}];//头像
                                
                                NSString *sign = @"";
                                [UserInfoManager configInfo:@{@"signAture":sign}];//个签
                                //发送登录通知
                                NSNotification *notification =[NSNotification notificationWithName:kNotifactionUserLogin object:nil userInfo:nil];
                                [[NSNotificationCenter defaultCenter] postNotification:notification];
                                // 退出界面
                                [self dismissViewControllerAnimated:YES completion:nil];
                            }else{
                                [MBProgressHUD showTipMessageInWindow:json[@"message"]];
                            }
                        } failure:^(NSError *error) {
                            NSString *str = [ECData_Json requestErrorTipWith:error];
                            [MBProgressHUD showTipMessageInWindow:str];
                        }];
                    }else{
                        [MBProgressHUD showTipMessageInWindow:@"请输入验证码"];
                    }
                }else{//密码不合法
                    [MBProgressHUD showTipMessageInWindow:kAlertTipOfPasswordValid];
                }
            }else{
                [MBProgressHUD showTipMessageInWindow:@"请设置用户名"];
            }
        }else{//不合法
            [MBProgressHUD showTipMessageInWindow:@"请输入有效的手机号"];
        }
    }else{//手机号为空
        [MBProgressHUD showTipMessageInWindow:@"请输入手机号"];
    }

}

/*  服务协议是否同意  */
-(void)selectBtn_click:(ECUButton *)btn{
    if (btn.selected) {
        btn.selected = NO;
        [btn setImage:[UIImage imageNamed:@"selectBtn_normal"] forState:0];
    }else{
        btn.selected = YES;
        [btn setImage:[UIImage imageNamed:@"selectBtn_select"] forState:0];
    }
}

-(void)agreeBtnClick{
    DLog(@"服务协议");
    [self.navigationController pushViewController:[ECPrivacyAgreementVc new] animated:YES];
}

-(void)action_dismiss{
    [self.navigationController popViewControllerAnimated:YES];
}

- (IBAction)returnBtnClcik:(ECUButton *)sender {
    [self.navigationController popViewControllerAnimated:YES];
}

-(void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
    [self.view endEditing:YES];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end
